package com.xj.opcua.Scheduled;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.google.common.collect.ImmutableList;
import com.xj.opcua.client.util.OpcUaClentUtils;
import com.xj.opcua.util.StringUtils;

@Component
public class OpcUaClientTask {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	public static final String url1 = "opc.tcp://49.72.111.139:53534/OPCUA/SCADA";
	
	//@Scheduled(initialDelay=1000*10,fixedRate=1000*5)
	public void browseNode(){
		OpcUaClient opcUaClient = OpcUaClentUtils.getOpcUaClent(url1);
		if(opcUaClient!=null) {
			List<Object[]> list = new ArrayList<Object[]>();
			NodeId nodeId = new NodeId(2, "Scada.Mes");
	        // 开始浏览节点
			list = OpcUaClentUtils.browseNode("", opcUaClient, nodeId,list,0);
			if(list!=null)
				logger.info("查询到的节点数为"+list.size());
		}
	}
	
	
	//@Scheduled(initialDelay=1000*10,fixedDelay=500)
	public void readValue(){
		OpcUaClient opcUaClient = OpcUaClentUtils.getOpcUaClent(url1);
		if(opcUaClient!=null) {
			NodeId nodeId = new NodeId(2, "\"DB_暂存库\".\"第2根料检测开关\"");
	        // 开始浏览节点
			Object value = OpcUaClentUtils.readValue(opcUaClient, nodeId);
			logger.info("查询到的节点值为"+value);
		}
	}
	
	//@Scheduled(initialDelay=1000*10,fixedDelay=500)
	public void readValues(){
		OpcUaClient opcUaClient = OpcUaClentUtils.getOpcUaClent(url1);
		if(opcUaClient!=null) {
			NodeId nodeId1 = new NodeId(2, "\"DB_暂存库\".\"第1根料检测开关\"");
			NodeId nodeId2 = new NodeId(2, "\"DB_暂存库\".\"第2根料检测开关\"");
			List<NodeId> nodeIds = ImmutableList.of(nodeId1, nodeId2);
			Map<NodeId, Object> map = OpcUaClentUtils.readValues(opcUaClient, nodeIds);
			logger.info("查询到的节点值为\"DB_暂存库\".\"第1根料检测开关\""+map.get(nodeId1));
			logger.info("查询到的节点值为\"DB_暂存库\".\"第2根料检测开关\""+map.get(nodeId2));
		}
	}
	
	//@Scheduled(initialDelay=1000*10,fixedDelay=5000)
	public void writeValue(){
		OpcUaClient opcUaClient = OpcUaClentUtils.getOpcUaClent(url1);
		if(opcUaClient!=null) {
			boolean write = false;
			NodeId nodeId = new NodeId(2, "\"DB_暂存库\".\"第2根料检测开关\"");
			Object value = OpcUaClentUtils.readValue(opcUaClient, nodeId);
			if("false".equalsIgnoreCase(StringUtils.toString(value))) {
				write = true;
			}
			Map<String, Object> map = new LinkedHashMap<String, Object>();
			map.put("\"DB_暂存库\".\"第2根料检测开关\"", write);
			OpcUaClentUtils.writeValue(opcUaClient, map,2);
		}
	}
	
}
